<?php

namespace backend\models;

use Yii;
use backend\models\School;
use yii\web\UploadedFile;

class SchoolCertificate extends \common\models\SchoolCertificate
{
    public function rules()
    {
        return array_merge([
            [['HDSJ', 'DJSJ'], 'date', 'format' => 'php:Y-m-d', 'message' => '错误的日期格式，请重新修改'],
            [['WJ'], 'file', 'extensions'=>'pdf,png,jpg,jpeg', 'maxSize' => 102400*2, /*'skipOnEmpty' => false*/],  // 只支持200k以内的pdf,png,jpg,jpeg文件
        ], parent::rules());
    }

    /////////////// 文件上传 ///////////////
    public function uploadedFile($model, $path)
    {       
        $file = UploadedFile::getInstance($model, 'WJ');

        if($file)   // 当提交表单时有选择文件
        {
            $schoolName = School::find()->where(['id' => $model->XXID])->one()->YWMC;

            // 创建 学校/分类 文件夹
            $schoolDir = $schoolName.'-'.$model['XXID'];
            $classDir = \Yii::$app->controller->id;
            if (!file_exists('upload/'.$schoolDir.'/'.$classDir)) {
                mkdir('upload/'.$schoolDir.'/'.$classDir, 0777, true);
            }

            // 文件上传（只支持200k以内的png,jpg,jpeg文件）
            $path = '/upload/'.$schoolDir.'/'.$classDir.'/'.md5(time().rand(0,9)).".".$file->getExtension();
            if($file->saveAs('/usr/share/nginx/html/web'.$path)) {
                /* *********** 旧文件再另外实现文件缓存清理机制、此处尚未实现 *********** */
                $model->WJ = $path;   // 将文件路径写入模型
            }
        }
        else      // 当提交表单时没有选择文件
        {
            $model->WJ = $path;
        }
        
        return $model;
    }

    /////////////// 生成/获取影子记录 ///////////////
    public function getShadowRecord($model)
    {
      $schoolSR = School::find()->select('ID')->where("DM = '$model->DM'")->andWhere(['not', "ZT = '正常'"])->one();  // 查询school表的影子记录   
      $certificateSR = SchoolCertificate::find()->where("XXID = '$model->ID'")->one();  // 查询该model参数ID对应的school-certificate记录
             
        if (!$schoolSR) // 无影子记录->新创建
        {
            $recordAsArray = $model->attributes;  // 提取school记录的数组数据
            unset($recordAsArray['ID']);  // 删除证照资质记录的数组数据中的ID字段，使新纪录ID可以自增
            $newSchoolRecord = new School( $recordAsArray );
            $newSchoolRecord->ZT = '修改';
            $newSchoolRecord->save(false);
            $schoolSR = School::find()->select('ID')->where("DM = '$model->DM'")->andWhere(['not', "ZT = '正常'"])->one();  // 此时已存在school表的影子记录，查询该记录的ID
            
            // 同时生成一条school-certificate的影子记录
            $newCertificateRecord = new SchoolCertificate();
            $newCertificateRecord->load(Yii::$app->request->post());  // 载入表单当前填写的数据
            $newCertificateRecord->XXID = $schoolSR->ID;  // 修改影子记录的XXID为school表相应的ID
            $newCertificateRecord = SchoolCertificate::uploadedFile($newCertificateRecord, $certificateSR->WJ);
            $newCertificateRecord->save();
            return $newCertificateRecord;
        }
        else  // 已存在影子记录
        {
            $WJ = $certificateSR->WJ;
            $certificateSR->load(Yii::$app->request->post());
            $certificateSR->WJ = $WJ;
            $certificateSR->update();  // 在提交审核之前的任意次修改依然生效
            return $certificateRecord;
        }
        
    }

    /////////////// 新建初始记录 ///////////////
    public function createNewRecord($id)
    {
        $schoolCertiModel = new SchoolCertificate();
        $schoolCertiModel->XXID = $id;
        $schoolCertiModel->ZZLB = '待补充';
        $schoolCertiModel->ZZMC = '待补充';
        $schoolCertiModel->WJ = '待补充';
        $schoolCertiModel->HDSJ = date('Y-m-d', time());
        $schoolCertiModel->DJSJ = date('Y-m-d', time());
        $schoolCertiModel->save(false);
        return $schoolCertiModel;
    }
}